import { Component, OnDestroy, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { NzMessageService, NzModalService, UploadFile } from 'ng-zorro-antd';
import { catchError } from 'rxjs/operators';
import { of } from 'rxjs/index';
import { PopService } from '../../../../service/pop/pop.service';
import { ProductService } from '../../../../service/prod/product.service';
import { CommService } from '../../../../service/comm/comm.service';
import { Constant, ServiceResult } from '@core/constant';
import { Router } from '@angular/router';
import { ActivatedRoute } from '@angular/router';
import { TranslateService } from '@ngx-translate/core';
import { EmitterService } from '../../../../service/emit.service';

@Component({
  selector: 'pop-list-add',
  templateUrl: './add.component.html',
  styleUrls: ['./add.component.less'],
})
export class PopListAddComponent implements OnInit, OnDestroy {
  validateForm: FormGroup;
  salestatus = false;
  attrList = [
    this.trans.instant('img'),
    'SAP',
    'SKU',
    // 'SAP名称',
    // this.trans.instant('description'),
    'EXW',
    'CIF',
    'QTY',
    this.trans.instant('ctn_qty'),
    this.trans.instant('gross_weight'),
    this.trans.instant('net_weight'),
    this.trans.instant('material'),
  ];
  priceUnits = [{ text: '$', value: 'USD' }, { text: '€', value: 'EUR' }];
  brands = [];
  pop: any = {
    id: null /*No show*/,
    sap: null,
    sku: null,
    description: null,
    img: null /*No show*/,
    unit: null /*No show*/,
    qty: null /*No show*/,
    netWeight: null,
    grossWeight: null,
    exw: null /*No show*/,
    cif: null /*No show*/,
    priceUnit: null,
    status: null,
    brand: null,
    ctnQty: null /*No show*/,
    cm: null,
    details: [],
  };

  dataTable = [];
  uploadUrl = '';
  imgSuffix = '';
  batch = [];
  // title = '修改POP套餐';

  pasteExcel(row, col, e) {
    let CHAR = '\r\n';
    if ('Windows' !== this.getOS()) {
      CHAR = '\n';
    }
    for (const item of e.clipboardData.items) {
      if (item.type === 'text/plain') {
        item.getAsString(text => {
          const x = col,
            y = row,
            obj = {};
          text = text.trim(CHAR);
          text.split(CHAR).forEach((v2, i2) => {
            v2.split('\t').forEach((v3, i3) => {
              const newRow = y + i2,
                newCol = x + i3;
              if (this.dataTable[newRow]) {
                this.dataTable[newRow][newCol] = v3;
              }
            });
          });
        });
      }
    }
  }
  batchEdit(index) {
    for (let row = 0; row < this.dataTable.length; row++) {
      this.dataTable[row][index] = this.batch[index];
    }
  }
  append() {
    if (this.dataTable.length >= 10) {
      return;
    }
    this.dataTable.push([]);
  }

  resetForm(e: MouseEvent): void {
    e.preventDefault();
    this.validateForm.reset();
    for (const key in this.validateForm.controls) {
      this.validateForm.controls[key].markAsPristine();
      this.validateForm.controls[key].updateValueAndValidity();
    }
  }

  constructor(
    private fb: FormBuilder,
    private trans: TranslateService,
    private popService: PopService,
    private msg: NzMessageService,
    private productService: ProductService,
    private comm: CommService,
    private cnt: Constant,
    private router: Router,
    private activatedRouter: ActivatedRoute,
    private emit: EmitterService,
  ) {}

  ngOnInit(): void {
    // 获取参数
    this.uploadUrl = this.productService.uploadUrl();
    this.imgSuffix = this.comm.getGoodsUrl();
    this.activatedRouter.params.subscribe(params => {
      this.pop.id = params['id'];
      if (this.pop.id === undefined) {
        return;
      }
      // if (
      //   this.pop.id != null ||
      //   this.pop.id !== '' ||
      //   this.pop.id !== undefined
      // ) {
      //   this.title = '修改POP套餐';
      // }
      // 获取POP详情
    });
    // 构建数据表 默认3行
    this.dataTable = [[], [], []];
    this.batch = [];
    this.loadBrands();
    this.getPopMaintenanceInfo();
    setTimeout(() => {
      this.emit.sendMessage('HIDE_REUSE_TAB');
    }, 100);
  }
  ngOnDestroy() {
    this.emit.sendMessage('SHOW_REUSE_TAB');
  }

  mergeStyleColor() {
    for (let row = 0; row < this.dataTable.length; row++) {
      if (this.dataTable[row][1] || this.dataTable[row][2]) {
        this.dataTable[row][3] = (
          this.dataTable[row][1] +
          '' +
          (this.dataTable[row][2] + '')
        ).replace('/', '');
      }
    }
  }
  getOS() {
    const userAgent = window.navigator.userAgent,
      platform = window.navigator.platform,
      macosPlatforms = ['Macintosh', 'MacIntel', 'MacPPC', 'Mac68K'],
      windowsPlatforms = ['Win32', 'Win64', 'Windows', 'WinCE'],
      iosPlatforms = ['iPhone', 'iPad', 'iPod'];
    let os = null;

    if (macosPlatforms.indexOf(platform) !== -1) {
      os = 'Mac OS';
    } else if (iosPlatforms.indexOf(platform) !== -1) {
      os = 'iOS';
    } else if (windowsPlatforms.indexOf(platform) !== -1) {
      os = 'Windows';
    } else if (/Android/.test(userAgent)) {
      os = 'Android';
    } else if (!os && /Linux/.test(platform)) {
      os = 'Linux';
    }

    return os;
  }

  previewImage = '';
  previewVisible = false;

  loading = false;
  // 预览图片地址
  picUrl = '';

  beforeUpload = (file: File) => {
    const isJPG = file.type === 'image/jpeg';
    const isPNG = file.type === 'image/png';
    if (!isJPG && !isPNG) {
      this.msg.create('warning', `不支持的格式: ${file.type}`);
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      this.msg.create('warning', '图片不能超过2MB!');
    }
    return (isJPG || isPNG) && isLt2M;
  };

  private getBase64(img: File, callback: (img: any) => void) {
    if (img) {
      const reader = new FileReader();
      reader.addEventListener('load', () => callback(reader.result));
      reader.readAsDataURL(img);
    }
  }

  handleChange(info: { file: UploadFile }): void {
    if (info.file.status === 'uploading') {
      this.loading = true;
      return;
    }
    if (info.file.status === 'done') {
      this.getBase64(info.file.originFileObj, (img: any) => {
        this.pop.img = info.file.response.rows[0].id;
        this.picUrl = this.comm.getGoodsUrl() + this.pop.img;
        this.loading = false;
      });
    }
    if (info.file.status === 'error') {
      this.msg.create('error', info.file.error.error);
    }
  }
  detailPicUrl = '';
  handleChangeForDetail(info: { file: UploadFile }, row): void {
    if (info.file.status === 'uploading') {
      this.loading = true;
      return;
    }
    if (info.file.status === 'done') {
      this.getBase64(info.file.originFileObj, (img: any) => {
        row[0] = info.file.response.rows[0].id;
        this.detailPicUrl = this.comm.getGoodsUrl() + row[0];
        this.loading = false;
      });
    }
    if (info.file.status === 'error') {
      this.msg.create('error', info.file.error.error);
    }
  }

  isBlank(str: string) {
    if (str == null || str === undefined || str === '') {
      return true;
    }
    return false;
  }

  save() {
    // 如果未设置主要的SKU、SAP、Description信息，则合并每个Detail中的对应信息，中间以&分隔
    if (this.isBlank(this.pop.brand)) {
      this.msg.create('error', '请选择品牌信息!');
      return;
    }
    let tmpSap = '';
    let tmpSku = '';
    // let tmpDescription = '';
    this.pop.details = [];
    this.pop.exw = 0;
    this.pop.cif = 0;
    this.pop.qty = null;
    this.pop.ctnQty = null;
    this.pop.grossWeight = null;
    this.pop.netWeight = null;
    this.pop.priceUnit = 'USD';
    for (const data of this.dataTable) {
      // 判断SAP号是否为空
      if (
        data[1] === null ||
        data[1] === '' ||
        data[1] === undefined ||
        data[1] === NaN
      ) {
        continue;
      } else {
        // 判断数量是否大于1
        if (this.isBlank(data[13])) {
          continue;
        }
        const detail = {
          img: data[0],
          sap: data[1],
          sku: data[2],
          // sapDesc: data[3],
          // description: data[4],
          exw: data[3],
          cif: data[4],
          qty: data[5],
          ctnQty: data[6],
          grossWeight: data[7],
          netWeight: data[8],
          material: data[9],
          id: data[10],
          priceUnit: data[11],
          popId: data[12],
          count: data[13],
          status: data[14],
        };
        console.log(detail);
        if (this.isBlank(detail.exw)) {
          detail.exw = 0;
        }
        if (this.isBlank(detail.cif)) {
          detail.cif = 0;
        }
        if (this.isBlank(detail.qty)) {
          detail.qty = 0;
        }
        if (this.isBlank(detail.ctnQty)) {
          detail.ctnQty = 0;
        }
        if (this.isBlank(detail.grossWeight)) {
          detail.grossWeight = 0;
        }
        if (this.isBlank(detail.netWeight)) {
          detail.netWeight = 0;
        }
        this.pop.exw += +detail.exw * detail.count;
        this.pop.cif += +detail.cif * detail.count;
        this.pop.qty += +detail.qty * detail.count;
        this.pop.grossWeight += +detail.grossWeight * detail.count;
        this.pop.netWeight += +detail.netWeight * detail.count;
        this.pop.ctnQty += +detail.ctnQty;
        this.pop.details.push(detail);
        // 设置临时存储信息
        if (
          detail.sku != null ||
          detail.sku !== undefined ||
          detail.sku !== ''
        ) {
          tmpSku += detail.sku + '&';
        }
        if (
          detail.sap != null ||
          detail.sap !== undefined ||
          detail.sap !== ''
        ) {
          tmpSap += detail.sap + '&';
        }
      }
    }
    this.pop.status = this.salestatus ? 'normal' : 'disabled';
    this.pop.unit = this.pop.unit != null ? '付' : this.pop.unit;
    if (this.isBlank(this.pop.sku)) {
      let sliceSku = '';
      if (tmpSku.endsWith('&')) {
        sliceSku = tmpSku.slice(0, -1);
        this.pop.sku = sliceSku;
      }
    }
    if (this.isBlank(this.pop.sap)) {
      let sliceSap = '';
      if (tmpSap.endsWith('&')) {
        sliceSap = tmpSap.slice(0, -1);
        this.pop.sap = sliceSap;
      }
    }
    // if (this.isBlank(this.pop.description)) {
    //   let sliceDesc = '';
    //   if (tmpDescription.endsWith('&')) {
    //     sliceDesc = tmpDescription.slice(0, -1);
    //     this.pop.description = sliceDesc;
    //   }
    // }
    console.log(this.pop);
    this.popService
      .save(this.pop)
      .pipe(
        catchError(err => {
          return of(err);
        }),
      )
      .subscribe(ret => {
        if (ret.status === 200 || ret.code === 200) {
          this.msg.create('success', '保存成功');
          this.router.navigate(['/pop/list/']);
        } else {
          if (ret.msg) {
            this.msg.create('error', ret.msg);
          } else {
            this.msg.create('error', ret.message);
          }
        }
      });
  }
  back() {
    this.router.navigate(['/pop/list']);
  }
  reset(i) {
    // 基本信息重置
    if (i === 0) {
      (this.pop.sap = null),
        (this.pop.sku = null),
        (this.pop.description = null),
        (this.pop.netWeight = null),
        (this.pop.grossWeight = null),
        (this.pop.priceUnit = null),
        (this.pop.status = null),
        (this.pop.brand = null),
        (this.pop.cm = null),
        (this.salestatus = true);
      this.pop.status = null;
    } else if (i === 1) {
      this.dataTable = [[], [], []];
      this.batch = [];
    }
  }

  public getPopMaintenanceInfo() {
    this.popService
      .listPopById(this.pop.id)
      .pipe(
        catchError(err => {
          return of(err);
        }),
      )
      .subscribe(ret => {
        if (ret.status === 200 || ret.code === 200) {
          this.pop = ret.data;
          this.salestatus = this.pop.status === 'normal';
          this.picUrl = this.comm.getGoodsUrl() + this.pop.img;
          const length = this.pop.details.length;
          // 判断长度是否大于默认表格行数，多就扩充
          if (length > this.dataTable.length) {
            const sub = length - this.dataTable.length;
            for (let i = 0; i < sub; i++) {
              if (this.dataTable.length >= 10) {
                break;
              }
              this.dataTable.push([]);
            }
          }
          this.pop.details.every((val, idx, array) => {
            this.dataTable[idx][0] = val.img;
            this.dataTable[idx][1] = val.sap;
            this.dataTable[idx][2] = val.sku;
            // this.dataTable[idx][3] = val.sapDesc;
            // this.dataTable[idx][4] = val.description;
            this.dataTable[idx][3] = val.exw;
            this.dataTable[idx][4] = val.cif;
            this.dataTable[idx][5] = val.qty;
            this.dataTable[idx][6] = val.ctnQty;
            this.dataTable[idx][7] = val.grossWeight;
            this.dataTable[idx][8] = val.netWeight;
            this.dataTable[idx][9] = val.material;
            this.dataTable[idx][10] = val.id;
            this.dataTable[idx][11] = val.priceUnit;
            this.dataTable[idx][12] = val.popId;
            this.dataTable[idx][13] = val.count;
            this.dataTable[idx][14] = val.status;
            return true;
          });
        }
      });
  }
  loadBrands() {
    const lang = this.trans.currentLang || this.trans.defaultLang;
    this.brands = [];
    this.comm.getBrand().subscribe(data => {
      const ret: ServiceResult = <ServiceResult>data;
      if (ret.status === 200) {
        for (const row of ret['data']['rows']) {
          this.brands.push({
            text: lang === 'en' ? row.labelEnUs : row.labelDefault,
            value: row.value,
          });
        }
      }
    });
  }
  minCount(row) {
    if (
      this.isBlank(this.dataTable[row][1]) ||
      this.dataTable[row].length === 0
    ) {
      return;
    }
    if (this.isBlank(this.dataTable[row][13])) {
      this.dataTable[row][13] = 0;
    }

    this.dataTable[row][13]--;
    if (this.dataTable[row][13] <= 1) {
      this.dataTable[row][13] = 1;
    }
  }
  addCount(row) {
    if (
      this.isBlank(this.dataTable[row][1]) ||
      this.dataTable[row].length === 0
    ) {
      return;
    }
    if (this.isBlank(this.dataTable[row][13])) {
      this.dataTable[row][13] = 0;
    }
    this.dataTable[row][13]++;
  }
}
